import 'dart:async';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_image_desc_widget.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_set_category_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_set_column_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_set_style_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:flutter/material.dart';
import 'package:keyboard_utils/keyboard_listener.dart';
import 'package:keyboard_utils/keyboard_utils.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import '../smart_home_category_response_bean.dart';
import '../smart_home_style_type_bean.dart';
import '../smart_home_upload_service.dart';


/// 上传图片批量设置
class SmartHomePublishImageBatchSettingPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomePublishImageBatchSettingPage";
  final String shid;
  final List<SmartHomeUploadItemBean> currentList;

  const SmartHomePublishImageBatchSettingPage({Key key, this.shid, this.currentList})
      : super(key: key);

  @override
  SmartHomePublishImageBatchSettingPageState createState() => SmartHomePublishImageBatchSettingPageState();

  ///跳转方法
  static Future<List<SmartHomeUploadItemBean>> navigatorPush(BuildContext context, String shid,
      List<SmartHomeUploadItemBean> currentList) {
    return RouterUtils.routeForFutureResult(
      context,
      SmartHomePublishImageBatchSettingPage(
        shid:shid,
        currentList:currentList,
      ),
      routeName: SmartHomePublishImageBatchSettingPage.ROUTER,
    );
  }
}

class SmartHomePublishImageBatchSettingPageState
    extends BaseState<SmartHomePublishImageBatchSettingPage>
    with
        AutomaticKeepAliveClientMixin,
        NavigatorPageMixin {

  ///获取state
  static SmartHomePublishImageBatchSettingPageState of(BuildContext context) {
    final SmartHomePublishImageBatchSettingPageState result =
    context.findAncestorStateOfType<SmartHomePublishImageBatchSettingPageState>();
    return result;
  }
  bool isAliveConfirm = false;

  List<SmartHomeUploadItemBean> _imageList = List();
  List<SmartHomeUploadItemBean> _originList = List();

  bool _selectAll = false;

  ColumnListBean _batchColumn = new ColumnListBean();
  SpatialTypeListBean _batchCategory = new SpatialTypeListBean();
  SmartHomeStyleTypeBean _batchStyle = new SmartHomeStyleTypeBean("", "");


  //栏目
  final List<ColumnListBean> _columnList = List();
  //空间
  final List<SpatialTypeListBean> _categoryList = List();
  //风格
  final List<SmartHomeStyleTypeBean> _styleList = List();

  SmartHomePublishViewModel _publishViewModel;
  KeyboardUtils _keyboardUtils = KeyboardUtils();
  @override
  void initState() {
    _keyboardUtils.add(listener: KeyboardListener(
        willHideKeyboard: (){
          FocusManager.instance.primaryFocus?.unfocus();
        },
        willShowKeyboard: (height){}
    ));
    super.initState();
    _publishViewModel = new SmartHomePublishViewModel(this);
    _imageList.addAll(widget?.currentList);
    _originList.addAll(widget?.currentList);

  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return LightAnnotatedRegion(
      child: Scaffold(
        backgroundColor: Colors.white,
        resizeToAvoidBottomPadding: false,
        resizeToAvoidBottomInset: false,
        body: _toMainColumnWidget(),
      ),
    );
  }
  /// 函数节流
  ///
  /// [func]: 要执行的方法
  Function throttle(
      Future Function() func,
      ) {
    if (func == null) {
      return func;
    }
    bool enable = true;
    Function target = () {
      if (enable == true) {
        enable = false;
        func().then((_) {
          enable = true;
        });
      }
    };
    return target;
  }
  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        _toSettingWidget(),
        Expanded(child: _toListWidget()),
        _toBottomWidget(),
        // Expanded(
        //   child: _toMainPlaceHolderWidget(),
        // )
      ],
    );
  }


  Widget _toTopBarWidget() {
    return Container(
      color: Color(0XFFF2F3F4),
      padding: EdgeInsets.only(top: ScreenUtils.getStatusBarH(context)),
      child: Container(
        height: 44,
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            Container(),
            Positioned(
              left: 0,
              child: ClickAnimateWidget(
                child: Container(
                  width: 40,
                  height: 44,
                  alignment: Alignment.centerLeft,
                  padding: const EdgeInsets.only(left: 15.6),
                  child: Image.asset(
                    "images/icon_close_volume_dialog.png",
                    width: 16.6,
                  ),
                ),
                scale: 1.4,
                onClick: () {
                  // VgNavigatorUtils.pop(context);
                  FocusScope.of(context).requestFocus(FocusNode());
                  Navigator.of(context).maybePop();
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 40.0, right: 40.0),
              child: Text(
                "批量设置",
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    fontSize: 17,
                    height: 1.22,
                    fontWeight: FontWeight.w600),
              ),
            ),
            Positioned(
              right: 0,
              child: _toSaveWidget(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toSaveWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        for(int i = 0; i < _originList.length; i++){
          if(_imageList.elementAt(i).selectStatus){
            _originList[i] = _imageList.elementAt(i);
          }
        }
        RouterUtils.pop(context, result: _originList);
      },
      child: Container(
        width: 60,
        height: 44,
        alignment: Alignment.center,
        child: Text(
          "完成",
          style: TextStyle(
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              fontSize: 15,
              fontWeight: FontWeight.w600),
        ),
      ),
    );
  }

  Widget _toSettingWidget(){
    return Container(
      height: 45,
      alignment: Alignment.center,
      child: Row(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              setState(() {
                _imageList.forEach((element) {
                  element.selectStatus = !_selectAll;
                });
                _selectAll = !_selectAll;
              });
            },
            child: Padding(
              padding: EdgeInsets.only(left: 14, right: 12),
              child: Text(
                _selectAll?"全不选":"全选",
                style: TextStyle(
                  fontSize: 14,
                  color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                ),
              ),
            ),
          ),
          Text(
            "已选${_getSelectedCount()}",
            style: TextStyle(
              fontSize: 12,
              color: Color(0XFF8B93A5),
            ),
          ),
        ],
      ),
    );
  }

  int _getSelectedCount(){
    int count = 0;
    if(_imageList != null){
      _imageList.forEach((element) {
        if(element.selectStatus??false){
          count++;
        }
      });
    }
    return count;
  }

  Widget _toListWidget(){
    return ScrollConfiguration(
        behavior: MyBehavior(),
        child: ListView.separated(
            padding: EdgeInsets.only(
                left: 0,
                right: 12,
                bottom: getNavHeightDistance(context)),
            itemCount: _imageList?.length ?? 0,
            physics: BouncingScrollPhysics(),
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
              return _toListItemWidget(context, index, _imageList?.elementAt(index));
            },
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(height: 24,);
            }
        ));
  }


  Widget _toListItemWidget(BuildContext context, int index, SmartHomeUploadItemBean itemBean) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            setState(() {
              itemBean.selectStatus = !(itemBean.selectStatus??false);
              _selectAll = _getSelectedCount() == _imageList.length;
            });
          },
          child: Container(
            height: 80,
            width: 44,
            alignment: Alignment.center,
            child: Image.asset(
              itemBean.selectStatus??false
                  ? "images/common_selected_ico.png"
                  : "images/common_unselect_ico.png",
              height: 20,
            ),
          ),
        ),
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: VgCacheNetWorkImage(
            itemBean?.getPicOrVideoUrl() ?? "",
            width: 80,
            height: 80,
            imageQualityType: ImageQualityType.middleDown,
          ),
        ),
        SizedBox(width: 8,),
        Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _toSelectColumnTypeStyleWidget(itemBean),
            SizedBox(height: 8,),
            SmartHomeImageDescWidget(itemBean: itemBean, width: ScreenUtils.screenW(context) - 144,),
          ],
        ),
      ],
    );
  }

  Widget _toSelectColumnTypeStyleWidget(SmartHomeUploadItemBean itemBean){
    return Container(
      width: ScreenUtils.screenW(context) - 144,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _toSelectColumnWidget(itemBean),
          _toSelectTypeWidget(itemBean),
          _toSelectStyleWidget(itemBean),
        ],
      ),
    );
  }

  ///选择类别
  Widget _toSelectColumnWidget(SmartHomeUploadItemBean itemBean){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_columnList.isNotEmpty){
          SmartHomePublishImageSetColumnDialog.navigatorPushDialog(context,
              itemBean?.scid,
              _columnList, (columnListBean){
                setState(() {
                  itemBean?.scid = columnListBean?.scid;
                  itemBean?.scidName = columnListBean?.name;
                });
              });
        }else{
          _publishViewModel.getLatestColumn(widget?.shid, (columnList){
            _columnList.addAll(columnList);
            SmartHomePublishImageSetColumnDialog.navigatorPushDialog(context,
                itemBean?.scid,
                _columnList, (columnListBean){
                  setState(() {
                    itemBean?.scid = columnListBean?.scid;
                    itemBean?.scidName = columnListBean?.name;
                  });
                });
          });
        }
      },
      child: Container(
        height: 26,
        width: 75,
        padding: EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          color: Colors.white,
          border: Border.all(
              color: Color(0XFFB0B3BF),
              width: 0.2
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            ConstrainedBox(
              constraints: BoxConstraints(
                maxWidth: 55,
              ),
              child: Text(
                StringUtils.isNotEmpty(itemBean?.scidName)?itemBean?.scidName:"类别",
                style: TextStyle(
                    fontSize: 13,
                    color: StringUtils.isNotEmpty(itemBean?.scidName)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFFB0B3BF)
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                softWrap: false,
              ),
            ),
            Spacer(),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }

  ///选择空间
  Widget _toSelectTypeWidget(SmartHomeUploadItemBean itemBean){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_categoryList.isNotEmpty){
          SmartHomePublishImageSetCategoryDialog.navigatorPushDialog(context,
              itemBean?.stid,
              _categoryList, (categoryListBean){
                setState(() {
                  itemBean?.stid = categoryListBean?.stid;
                  itemBean?.stidName = categoryListBean?.name;
                });
              });
        }else{
          _publishViewModel.getLatestCategory(widget?.shid, (categoryList){
            _categoryList.addAll(categoryList);
            SmartHomePublishImageSetCategoryDialog.navigatorPushDialog(context,
                itemBean?.stid,
                _categoryList, (categoryListBean){
                  setState(() {
                    itemBean?.stid = categoryListBean?.stid;
                    itemBean?.stidName = categoryListBean?.name;
                  });
                });
          });
        }
      },
      child: Container(
        height: 26,
        width: 75,
        padding: EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          color: Colors.white,
          border: Border.all(
              color: Color(0XFFB0B3BF),
              width: 0.2
          ),
        ),
        child: Row(
          children: [
            ConstrainedBox(
              constraints: BoxConstraints(
                maxWidth: 55,
              ),
              child: Text(
                StringUtils.isNotEmpty(itemBean?.stidName)?itemBean?.stidName:"空间",
                style: TextStyle(
                    fontSize: 13,
                    color: StringUtils.isNotEmpty(itemBean?.stidName)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFFB0B3BF)
                ),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                softWrap: false,
              ),
            ),
            Spacer(),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }

  ///选择风格
  Widget _toSelectStyleWidget(SmartHomeUploadItemBean itemBean){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_styleList.isNotEmpty){
          SmartHomePublishImageSetStyleDialog.navigatorPushDialog(context,
              itemBean?.style,
              _styleList, (styleBean){
                setState(() {
                  itemBean?.style = styleBean?.style;
                  itemBean?.styleName = styleBean?.name;
                });
              });
        }else{
          _publishViewModel.getLatestStyle(widget?.shid, (styleList){
            _styleList.addAll(styleList);
            SmartHomePublishImageSetStyleDialog.navigatorPushDialog(context,
                itemBean?.style,
                _styleList, (styleBean){
                  setState(() {
                    itemBean?.style = styleBean?.style;
                    itemBean?.styleName = styleBean?.name;
                  });
                });
          });
        }
      },
      child: Container(
        height: 26,
        width: 75,
        padding: EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          color: Colors.white,
          border: Border.all(
              color: Color(0XFFB0B3BF),
              width: 0.2
          ),
        ),
        child: Row(
          children: [
            ConstrainedBox(
              constraints: BoxConstraints(
                maxWidth: 55,
              ),
              child: Text(
                StringUtils.isNotEmpty(itemBean?.getStyleName())?itemBean?.getStyleName():"风格",
                style: TextStyle(
                    fontSize: 13,
                    color: StringUtils.isNotEmpty(itemBean?.getStyleName())?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFFB0B3BF)
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                softWrap: false,
              ),
            ),
            Spacer(),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }


  Widget _toBottomWidget(){
    final double bottomH = ScreenUtils.getBottomBarH(context);
    return Container(
      padding: EdgeInsets.only(bottom: bottomH),
      decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
                color: Color(0xff000000).withOpacity(0.2),
                offset: Offset(0, -1),
                blurRadius: 10
            )
          ]
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _toCommonFunctionWidget("类别", "icon_sm_column", (){
            if(_columnList.isNotEmpty){
              SmartHomePublishImageSetColumnDialog.navigatorPushDialog(context,
                  _batchColumn?.scid,
                  _columnList, (columnListBean){
                    setState(() {
                      _batchColumn?.scid = columnListBean?.scid;
                      _batchColumn?.name = columnListBean?.name;
                      setItemColumnByPackageColumn();
                    });
                  });
            }else{
              _publishViewModel.getLatestColumn(widget?.shid, (columnList){
                _columnList.addAll(columnList);
                SmartHomePublishImageSetColumnDialog.navigatorPushDialog(context,
                    _batchColumn?.scid,
                    _columnList, (columnListBean){
                      setState(() {
                        _batchColumn?.scid = columnListBean?.scid;
                        _batchColumn?.name = columnListBean?.name;
                        setItemColumnByPackageColumn();
                      });
                    });
              });
            }
          }),
          _toCommonFunctionWidget("空间", "icon_sm_type", (){
            if(_categoryList.isNotEmpty){
              SmartHomePublishImageSetCategoryDialog.navigatorPushDialog(context,
                  _batchCategory?.stid,
                  _categoryList, (categoryListBean){
                    setState(() {
                      _batchCategory?.stid = categoryListBean?.stid;
                      _batchCategory?.name = categoryListBean?.name;
                      setItemCategoryByPackageColumn();
                    });
                  });
            }else{
              _publishViewModel.getLatestCategory(widget?.shid, (categoryList){
                _categoryList.addAll(categoryList);
                SmartHomePublishImageSetCategoryDialog.navigatorPushDialog(context,
                    _batchCategory?.stid,
                    _categoryList, (categoryListBean){
                      setState(() {
                        _batchCategory?.stid = categoryListBean?.stid;
                        _batchCategory?.name = categoryListBean?.name;
                        setItemCategoryByPackageColumn();
                      });
                    });
              });
            }
          }),
          _toCommonFunctionWidget("风格", "icon_sm_style", (){
            if(_styleList.isNotEmpty){
              SmartHomePublishImageSetStyleDialog.navigatorPushDialog(context,
                  _batchStyle?.style,
                  _styleList, (styleBean){
                    setState(() {
                      _batchStyle?.style = styleBean?.style;
                      _batchStyle?.name = styleBean?.name;
                      setItemStyleByPackageColumn();
                    });
                  });
            }else{
              _publishViewModel.getLatestStyle(widget?.shid, (styleList){
                _styleList.addAll(styleList);
                SmartHomePublishImageSetStyleDialog.navigatorPushDialog(context,
                    _batchStyle?.style,
                    _styleList, (styleBean){
                      setState(() {
                        _batchStyle?.style = styleBean?.style;
                        _batchStyle?.name = styleBean?.name;
                        setItemStyleByPackageColumn();
                      });
                    });
              });
            }
          }),
        ],
      ),
    );
  }

  ///子item设置为整体设置的属性
  void setItemColumnByPackageColumn(){
    _imageList.forEach((element) {
      if(element.selectStatus){
        element.scid = _batchColumn.scid;
        element.scidName = _batchColumn.name;
      }
    });
  }

  ///子item设置为整体设置的属性
  void setItemCategoryByPackageColumn(){
    _imageList.forEach((element) {
      element.stid = _batchCategory.stid;
      element.stidName = _batchCategory.name;
    });
  }

  ///子item设置为整体设置的属性
  void setItemStyleByPackageColumn(){
    _imageList.forEach((element) {
      element.style = _batchStyle.style;
      element.styleName = _batchStyle.name;
    });
  }


  ///通用样式
  Widget _toCommonFunctionWidget(String title, String asset, Function callback){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_getSelectedCount() < 1){
          return;
        }
        callback.call();
      },
      child: Container(
        height: 70,
        alignment: Alignment.center,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Opacity(
              opacity: _getSelectedCount() > 0?1:0.5,
              child: Image.asset(
                "images/${asset}.png",
                width: 26,
              ),
            ),
            SizedBox(height: 6,),
            Text(
              title,
              style: TextStyle(
                color: _getSelectedCount() > 0?ThemeRepository.getInstance().getLineColor_3A3F50():ThemeRepository.getInstance().getLineColor_3A3F50().withOpacity(0.5),
                fontSize: 10,
              ),
            ),
          ],
        ),
      ),
    );
  }



  @override
  bool get wantKeepAlive => true;
}
